<?php
define("TOKEN", "tanghn");
/*返回最大记录数*/
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();

function DEBUGINFO($abc)
{
	@ $fp = fopen("debug.txt", 'ab');
	fwrite($fp, $abc);
	fclose($fp);
}

class wechatCallbackapiTest
{
	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

      	//extract post data
		if (!empty($postStr)){
			$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
			$fromUsername = $postObj->FromUserName;
			$toUsername = $postObj->ToUserName;
			$content = trim($postObj->Content);
			
			$result = file_get_contents("http://tanghn.xicp.net/recv.php?from=".$fromUsername."&to=".$toUsername."&cont=".$content);

			echo $result;
			
			DEBUGINFO("write to weixin:\r\n");
			DEBUGINFO($result);
			
        }else {
        	echo "222222";
        }
		
		exit;
    }
		
	private function checkSignature()
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

?>